<template>
  <l-data-panel :label="data.title" isApp>
    <l-echarts ref="main" :option="option"></l-echarts>
  </l-data-panel>
</template>
<script>
export default {
  props: ["data", "isPreview", "isShow"],
  data() {
    return {
      option: {
        tooltip: {
          trigger: "item",
        },
        legend: {
          orient: "vertical",
          left: "left",
        },
        series: [
          {
            name: "",
            type: "pie",
            radius: "50%",
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      },
      timer: null,
    };
  },
  watch: {
    isShow() {
      setTimeout(() => {
        this.$refs.main.updateChart();
      }, 100);
    },
    data: {
      handler() {
        this.refresh();
      },
      deep: true,
    },
  },
  mounted() {
    this.refresh();
  },
  methods: {
    async getOption() {
      this.option.series[0].name = this.data.label;
      // 加载数据
      if (this.data.dataCode) {
        await this.lr_loadDataSourceData(this.data.dataCode, !!this.isPreview);
      }

      const data = this.lr_dataSourceData[this.data.dataCode] || [];

      if (this.data.nameKey && this.data.valueKey) {
        this.option.series[0].data = data.map((t) => {
          return { name: t[this.data.nameKey], value: t[this.data.valueKey] };
        });
      }

      return this.option;
    },
    refresh() {
      if (this.timer == null) {
        this.timer = setTimeout(async () => {
          const option = await this.getOption();
          this.$refs.main.updateChart(option);
          this.timer = null;
        }, 100);
      }
    },
  },
};
</script>

